<script setup>
import {RegisterDevice} from "../../wailsjs/go/api/DeviceApi.js"
import {GetImage} from "../../wailsjs/go/api/FileSystem.js";
import {
  GetCustomerInfoById,
} from "../../wailsjs/go/api/CustomerApi.js";
import { SaveToken, GetUserOrganList } from "../../wailsjs/go/api/AuthApi.js";
import {
  CheckCameraAvailability,StopCameraCaptureForClient,
  FaceMeasurement,CameraCapture
} from "../../wailsjs/go/api/CameraApi.js";
import {
  ListTreeChecklistInfos,
  QueryChecklistInfoById,
} from "../../wailsjs/go/api/ReportApi.js";
import { ref, onMounted } from 'vue'

// WebSocket 连接引用
const ws1 = ref(null)
const ws2 = ref(null)
const ws3 = ref(null)

// Canvas 引用和上下文
const videoCanvas1 = ref(null)
const videoCanvas2 = ref(null)
const videoCanvas3 = ref(null)
const ctx1 = ref(null)
const ctx2 = ref(null)
const ctx3 = ref(null)

// 摄像头ID
const cid1 = ref('')
const cid2 = ref('')
const cid3 = ref('')
// 初始化Canvas
const initCanvas = () => {
  // 初始化摄像头1的Canvas
  if (videoCanvas1.value) {
    const canvas = videoCanvas1.value
    canvas.width = canvas.clientWidth
    canvas.height = canvas.clientHeight
    ctx1.value = canvas.getContext('2d', { willReadFrequently: false })
  }
  // 初始化摄像头2的Canvas
  if (videoCanvas2.value) {
    const canvas = videoCanvas2.value
    canvas.width = canvas.clientWidth
    canvas.height = canvas.clientHeight
    ctx2.value = canvas.getContext('2d', { willReadFrequently: false })
  }

  if (videoCanvas3.value) {
    const canvas = videoCanvas3.value
    canvas.width = canvas.clientWidth
    canvas.height = canvas.clientHeight
    ctx3.value = canvas.getContext('2d', { willReadFrequently: false })
  }
}

// 启动摄像头
const startCamera = async (id) => {
  const wsUrl = `ws://localhost:8090/ws?camera_id=${id}`
    if (ws1.value && ws1.value.readyState === WebSocket.OPEN) {
      console.log('摄像头1已经启动')
      return
    }
    ws1.value = new WebSocket(wsUrl)
    ws1.value.onopen = () => console.log('摄像头1 WebSocket连接已建立')
    ws1.value.onmessage = handleMessage1
    ws1.value.onerror = handleError1
    ws1.value.onclose = () => console.log('摄像头1 WebSocket连接已关闭')
}

// 启动文字流
const startTipsFlow = async () => {
  const wsUrl = `ws://localhost:8090/ws?camera_id=1&camera_type=tips`
  if (ws2.value && ws2.value.readyState === WebSocket.OPEN) {
    console.log('摄像头2已经启动')
    return
  }
  ws2.value = new WebSocket(wsUrl)
  ws2.value.onopen = () => console.log('摄像头1 WebSocket连接已建立')
  ws2.value.onmessage = handleTipsMessage
  ws2.value.onerror = handleError1
  ws2.value.onclose = () => console.log('摄像头1 WebSocket连接已关闭')
}

// 停止摄像头
const stopCamera = (id) => {
  if (id === 1 && ws1.value) {
    StopCameraCaptureForClient(cid1.value)
    ws1.value.close()
    ws1.value = null
    cid1.value = ''
    console.log('摄像头1已停止')
  }else if (id === 2 && ws2.value) {
    StopCameraCaptureForClient(cid2.value)
    ws2.value.close()
    ws2.value = null
    cid2.value = ''
    console.log('摄像头1已停止')
  }
}

// 处理摄像头1的消息
const handleMessage1 = (event) => {
  // 第一帧数据
  if (typeof event.data === "string") {
    const header = JSON.parse(event.data)
    if (header.type === "ping") {
      cid1.value = header.cid
      console.log(`摄像头CID:`, header.cid)
    }
  }
  ws1.value.binaryType = "arraybuffer"
  processWebSocketMessage(event, 1)
}

const handleTipsMessage = (event) => {
  if (typeof event.data === "string") {
    const header = JSON.parse(event.data)
    if (header.type === "ping") {
      cid2.value = header.cid
      console.log(`handleTipsMessage CID:`, header.cid)
    }
  }
  // ws1.value.binaryType = "text"
  const tips = JSON.parse(event.data)
  console.log("tips:",tips)
}


// 统一的WebSocket消息处理
const processWebSocketMessage = (event, cameraId) => {
  // if (typeof event.data === "string") {
  //   const header = JSON.parse(event.data)
  //   if (header.type === "ping") {
  //      cid1.value = header.cid
  //     console.log(`摄像头${cameraId} CID:`, header.cid)
  //   } else if (header.type === "data") {
  //       ws1.value.binaryType = "arraybuffer"; //下一个消息是二进制视频数据
  //   }
  // } else if (event.data instanceof ArrayBuffer) {
  //   renderFrame(event.data, cameraId)
  // }
  // 只处理二进制消息（无需处理字符串）
  if (!(event.data instanceof ArrayBuffer)) {
    return;
  }
  const buffer = event.data;
  const view = new DataView(buffer);
  // 1. 读取前 4 字节（小端）获取 JPEG 数据长度
  const jpegLength = view.getUint32(0, true); // true 表示小端
  // 2. 提取 JPEG 数据（从第 4 字节开始，长度为 jpegLength）
  const jpegBuffer = buffer.slice(4, 4 + jpegLength);
  renderFrame(jpegBuffer, cameraId)
}

// 渲染视频帧
const renderFrame = (arrayBuffer, cameraId) => {
  const blob = new Blob([arrayBuffer], { type: "image/jpeg" })
  const imageUrl = URL.createObjectURL(blob)
  const img = new Image()
  img.onload = () => {
    let ctx = null
    ctx = ctx1.value
    let canvas = null
    canvas = videoCanvas1.value

    if (ctx && canvas) {
      // 清除画布
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      // 计算缩放比例，保持图片比例
      const scale = Math.min(canvas.width / img.width, canvas.height / img.height)
      const width = img.width * scale
      const height = img.height * scale
      const x = (canvas.width - width) / 2
      const y = (canvas.height - height) / 2
      // 绘制图像
      ctx.drawImage(img, x, y, width, height)
    }
    // 释放对象URL
    URL.revokeObjectURL(imageUrl)
  }

  img.onerror = () => {
    console.error(`摄像头${cameraId} 图像加载失败`)
    URL.revokeObjectURL(imageUrl)
  }

  img.src = imageUrl
}

// 错误处理
const handleError1 = (error) => {
  console.error('摄像头1 WebSocket错误:', error)
}

// const cleanup = () => {
//   stopCamera(1)
//   stopCamera(2)
// }

onMounted(() => {
  initCanvas()
})

</script>

<template>
  <main>
      <div class="left-camera" style="display: flex;flex-direction: column;align-items: center;">
        <div>
          middle
        </div>
        <div class="content">
          <canvas ref="videoCanvas1"></canvas>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 10px;">
          <button style="margin-right: 20px;" @click="startCamera(1)">startCamera</button>
          <button @click="stopCamera(1)">stopCamera</button>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 10px;">
          <button style="margin-right: 20px;" @click="startTipsFlow">startTipsFlow</button>
          <button @click="stopCamera(2)">stopTipsFlow</button>
        </div>
      </div>
  </main>
</template>

<style scoped lang="scss">
.hello {
  button {
    border: 2px solid #c4c4c4;
    margin-right: 20px;
  }
}
.left-camera {
  .content {
    margin-bottom: 10px;
    min-height: 300px;
    width: 100%;
    border: 1px solid black;
    position: relative;
    aspect-ratio: 16/9; /* 保持固定宽高比 */
    canvas {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%!important;
      height: 100%!important;
    }
  }

  .left-camera-1 {
    .content {
      margin-bottom: 10px;
      min-height: 600px;
      width: 100%;
      border: 1px solid black;
      position: relative;
      aspect-ratio: 16/9; /* 保持固定宽高比 */

      canvas {
        position: absolute;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100% !important;
      }
    }
  }

  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>